package com.todo.event.activity.application.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.common.utils.DateUtils;
import com.todo.common.utils.StringUtils;
import com.todo.event.activity.application.entity.bo.EventDetailBO;
import com.todo.event.activity.application.entity.context.FieldTransferContext;
import com.todo.event.activity.application.entity.model.EventInfoModel;
import com.todo.event.activity.application.handler.fieldtransfer.AbstractFieldTransferHandle;
import com.todo.event.activity.application.handler.fieldtransfer.FieldTransferFactory;
import com.todo.event.activity.common.enums.EventFieldDataSourceEnum;
import com.todo.event.activity.common.enums.EventFieldTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author azhebuxing
 * @date 2025/1/13 23:27
 * @description
 */
@Slf4j
@Component
public class EventDataService {

    @Value("#{'${event.mast.exist.field:userId}'.split(',')}")
    private List<String> mastExistField;

    @Resource
    private FieldTransferFactory fieldTransferFactory;


    public EventInfoModel buildAndeGetExecuteModel(EventDetailBO eventDetailBO, JSONObject payload) {
        String baseRule = eventDetailBO.getEventInfo().getRule();
        //事件准入规则验证-准入规则默认使用QL
        if (StringUtils.isNotBlank(baseRule)){
            AbstractFieldTransferHandle handle = fieldTransferFactory.getHandle(EventFieldDataSourceEnum.QLEXPRESS);
            FieldTransferContext context = new FieldTransferContext();
            context.setTransfer(baseRule);
            context.setDataSource(EventFieldDataSourceEnum.QLEXPRESS);
            context.setPayload(payload);
            String result = handle.fieldTransfer(context);
            if (!Boolean.parseBoolean(result)){
                log.warn("EventDataService#buildAndeGetExecuteModel 数据转化失败，准入规则不通过，context:【{}】,result:【{}】", JSONObject.toJSONString(context),result);
                throw new BizException(BizErrorCodeEnum.EVENT_DETAIL_ACCESS_RULE_ERROR, "准入规则不通过");
            }
        }
        List<EventDetailBO.EventField> eventFieldList = eventDetailBO.getEventFieldList();
        JSONObject newPayload = new JSONObject();
        EventInfoModel model = new EventInfoModel();
        for (EventDetailBO.EventField eventField : eventFieldList) {
            AbstractFieldTransferHandle handle = fieldTransferFactory.getHandle(eventField.getDataSource());
            if (handle == null) {
                continue;
            }
            FieldTransferContext context = new FieldTransferContext();
            context.setTransfer(eventField.getTransfer());
            context.setDataSource(eventField.getDataSource());
            context.setPayload(payload);
            String newValue = handle.fieldTransfer(context);
            //如果为唯一键，必须要有值
            if (eventField.getUniqueField() && StringUtils.isBlank(newValue)) {
                log.error("EventDataService#buildAndeGetExecuteModel 数据转化失败，唯一键为空，context:【{}】", JSONObject.toJSONString(context));
                throw new BizException(BizErrorCodeEnum.CORE_FIELD_MISSING, "唯一键为空");
            }
            if (newValue == null) {
                continue;
            }
            //设置当前唯一值
            if (eventField.getUniqueField()) {
                model.setUk(newValue);
                newPayload.put("uk", convertNewFieldValue(newValue, eventField.getFieldType()));
            }
            newPayload.put(eventField.getFieldName(), convertNewFieldValue(newValue, eventField.getFieldType()));
        }
        for (String mastField : mastExistField) {
            if (!newPayload.containsKey(mastField)) {
                log.error("EventDataService#buildAndeGetExecuteModel 数据转化失败，核心数据缺失，newPayload:【{}】", JSONObject.toJSONString(newPayload));
                throw new BizException(BizErrorCodeEnum.CORE_FIELD_MISSING, "核心数据缺失");
            }
        }
        model.setNewPayload(newPayload);
        model.setEventCode(eventDetailBO.getEventCode());
        model.setEventName(eventDetailBO.getEventInfo().getEventName());
        model.setTopicName(eventDetailBO.getEventInfo().getTopicName());
        model.setTag(eventDetailBO.getEventInfo().getTag());
        model.setConsumerName(eventDetailBO.getEventInfo().getConsumerName());
        model.setQueueType(eventDetailBO.getEventInfo().getQueueType());
        return model;
    }


    private Object convertNewFieldValue(String newValue, EventFieldTypeEnum fieldType) {
        switch (fieldType) {
            case STRING:
                return newValue;
            case LONG:
                return Long.parseLong(newValue);
            case DOUBLE:
                return Double.parseDouble(newValue);
            case ARRAY:
                return JSONObject.parseArray(newValue);
            case BOOLEAN:
                return Boolean.parseBoolean(newValue);
            case DATE:
                return DateUtils.dateTime(newValue, DateUtils.YYYY_MM_DD_HH_MM_SS);
            case DECIMAL:
                return new BigDecimal(newValue);
            case OBJECT:
                return JSONObject.parseObject(newValue);
            default:
                return newValue;
        }
    }

}
